# -*- coding: utf-8 -*-
"""
Created on Sat Jun 24 14:06:33 2017

@author: Administrator
"""


import datetime
import os
import re
import xlwt

check_nikname_dict =  {'宋小楠': '宋雅楠', '传言': '张传严', '章': '章解空',
                       '桂鹏': '黄桂鹏', '壮卫': '陈壮卫', '乐伊': '钟丽冰', 
                       '红姐': '陈红','永聪': '许永聪','凌燕': '陈凌燕', 
                       '曦扬': '原曦扬', '天一': '邹天一', '钊烽': '刘钊烽'}

all_name_set = {'安建朋', '陈壮卫', '梁锦辉', '张翔', '林灵', '张传严', '彭寒',
           '张丽娟', '钟丽冰', '许永聪', '陈红', '马宇荻', '李逸', '陈凌燕', 
           '姚铭乐', '周明灵', '陈晓纯', '宋雅楠', '吴海婷', '张凯豪', '廖淑坚',
           '戴丽婷', '陈菲儿', '农思雯', '唐小琴', '余汪洋', '郑镜培', '汤晨威',
           '黄鹏华', '粟正亭', '梁家辉', '温镓瑜', '常乐', '黄晓东', '陈峰', '袁平', 
           '黄桂鹏', '黄煜富', '张煜姗', '余祎玲', '邝佩贞', '胡旺', '黄治平', 
           '黄怡秋', '张琳', '周彩虹', '吴刘泽帆', '陈建全', '黄文杰', '尹宝君', 
           '张绍金', '张迪萌', '胡娟', '黄乒乒', '邹天一', '李松嵘', '胡楚龄', 
           '张巧改', '郭祥豪', '陈晓云', '陈丹静', '陈政', '陈奕', '苏宇哲', '钟鸣', 
           '罗凌飞', '李杨', '原曦扬', '冼康筠', '黄俊杰', '李静', '陆洋', '曾文星', 
           '朱城城', '郭欢', '梁宇明', '辜少萍', '邓韩', '许树添', '陈若雯', '欧文鑫', 
           '章解空', '王振明', '陈泳霖', '刘钊烽'}


def compare_time(file_name):
    """考虑把同一个目录里的所有log文件都当做要处理的文件
    """
    today = datetime.date.today()
    file_path = os.path.dirname(file_name)
    name = file_name[len(file_path)+1:]
    file_date_list = name.split(".")
    if file_date_list[1] == 'log':
      file_date = datetime.datetime.strptime(file_date_list[0], "%Y_%m_%d").date()
      if file_date <= today:
        return True
      else:
        return False
        

"""
get_sport_file: 函数
param: rootdir - 当前执行路径
return： 返回符合统计条件的文件列表
"""     
def get_sport_file(rootdir):
  sport_file = []
  for p, d, f in os.walk(rootdir):
    for i in f:
      file_name = os.path.join(p, i)
      if compare_time(file_name):
        sport_file.append(file_name) 
  return (sport_file)


"""
read_sport_file : 函数
param: file_name - 数据文件名，绝对路径
return:  results - 返回整个文件匹配正则后的内容，已经对时间进行处理
"""
def read_sport_file(file_name):
  '''正则匹配格式 "hh:mm nn name  walknums"
  '''
  xx = u"([0-9]+:[0-9]+).*?([0-9]+).*?([\u4e00-\u9fa5]+).*?([0-9]+)"
  
  '''正则匹配格式："YYYY-MM-dd" 年-月-日
  '''
  yy = u".*?([0-9]+-[0-9]+-[0-9]+).*?"
  
  results = [] 
  with open(file_name, 'rb') as fd:
    f = fd.read()
    f = f.decode('utf-8')
    
    two_date_time = re.findall(yy, f, re.S)
    print (two_date_time)
    if len(two_date_time) >= 2:
      first_part = f.split(two_date_time[1])[0]
      second_part = f.split(two_date_time[1])[1]
    
      first_part_results = re.findall(xx, first_part, re.S)
      second_part_results = re.findall(xx, second_part, re.S)
    
      for one_stuff in first_part_results:
        one_stuff_list = []
        one_stuff_list.append(two_date_time[0] +" " + one_stuff[0])
        one_stuff_list.append(one_stuff[1])
        one_stuff_list.append(one_stuff[2])
        one_stuff_list.append(one_stuff[3])
        results.append(one_stuff_list)
      for one_stuff_d in second_part_results:
        one_stuff_list = []
        one_stuff_list.append(two_date_time[1] +" " + one_stuff_d[0])
        one_stuff_list.append(one_stuff_d[1])
        one_stuff_list.append(one_stuff_d[2])
        one_stuff_list.append(one_stuff_d[3])
        results.append(one_stuff_list)
    elif len(two_date_time) == 1:
      first_part = f
      first_part_results = re.findall(xx, first_part, re.S)
      
      for one_stuff in first_part_results:
        one_stuff_list = []
        one_stuff_list.append(two_date_time[0] +" " + one_stuff[0])
        one_stuff_list.append(one_stuff[1])
        one_stuff_list.append(one_stuff[2])
        one_stuff_list.append(one_stuff[3])
        results.append(one_stuff_list)
  return (results)

 
"""
save_to_xls: 函数, 用于批量保存文件
result_dict: 输入参数，包含了文件名（日期形式的结构），以及员工的打卡信息
             {"2017_06_24": {"name": [walk, time],...}, "2017_06_25":{"name": [walk, time],...}, ... }
"""
def filter_name_time(result_dict):
  """保存文档前，先过滤重复的打卡记录，转换全名,以及过滤时间超时的记录
  """
  name_and_walknum = {}
  filename_all_stuff_walknum = {}
  for k_file_name, v_all_info in result_dict.items():
    '''stuff_info : example: ['2017-06-27 02:54', '81', '小明', '7789']
    '''
    for stuff_info in v_all_info:
      name = stuff_info[2]
      if name in all_name_set:
        name_and_walknum[name] = [ stuff_info[3],  stuff_info[0] ]
      elif name in check_nikname_dict:
        name_and_walknum[ check_nikname_dict[name] ] = [ stuff_info[3],  stuff_info[0] ]
      else:
        name_and_walknum[name] = [ stuff_info[3],  stuff_info[0] ]
    filename_all_stuff_walknum [k_file_name] = name_and_walknum

  return (filename_all_stuff_walknum)
  

def  save_to_xls(filename_all_stuff_walknum):                              
  style_normal = xlwt.XFStyle()
  font = xlwt.Font()
  font.name = 'SimSun'
  style_normal.font = font
  
  style_yellowBg = xlwt.easyxf('pattern: pattern solid, fore_colour yellow; font: bold on;');
                              
  for k_filename, v_all_stuff in filename_all_stuff_walknum.items():
    book = xlwt.Workbook(encoding='utf-8', style_compression=0)
    sheet = book.add_sheet(k_filename, cell_overwrite_ok=True)
    i = 0
    stander_time = k_filename + " " + "06:00"
    stander_time = datetime.datetime.strptime( stander_time, "%Y_%m_%d %H:%M")
    if i==0:
      sheet.write(i, 0, "dtEventTime")
      sheet.write(i, 1, "stuffName")
      sheet.write(i, 2, "walkNum")
      sheet.write(i, 3, "status")
    
    for k, v  in v_all_stuff.items():
      info_list = []
      i += 1
      stuff_name = k      
      stuff_walk_num = v[0]
      stuff_time_stamp = v[1]
      
      real_time = datetime.datetime.strptime(stuff_time_stamp, "%Y-%m-%d %H:%M")
      status = 'Nan'
      if real_time >= stander_time:
        style = style_yellowBg
        status = 'bad'
      else:
        style = style_normal
        status = 'good'
      info_list = [stuff_time_stamp, stuff_name, stuff_walk_num, status]  
      for j in range(4):
        sheet.write(i, j, info_list[j], style)
#        if j == 0 :
#          sheet.write(i, j, stuff_time_stamp, style)
#        elif j == 1 :
#          sheet.write(i, j, stuff_name, style)
#        elif j == 2 :
#          sheet.write(i, j, stuff_walk_num, style)      
    xl_name = str(k_filename) +".xls" 
    book.save(xl_name)

      
if __name__ == '__main__':
  
  rootdir = os.path.abspath(os.curdir) + '\\'  
  sport_files = get_sport_file(rootdir)
  
  for file_name in sport_files:
    result_dict = {}
    results = []
    ret_list = read_sport_file(file_name)
    
    """
    results     ： 每次只处理一份文件，所以results只包含了一个log文件的数据
    result_dict ： 将results转为字典，
                   结构内容:{"2017_06_24": [[time,seq,name, walk_num],...]}
    """
    results.extend(ret_list)
    file_path = os.path.dirname(file_name)
    name = file_name[len(file_path)+1:].split(".")[0]
    result_dict[name] = results
#    print(len(result_dict))
    
    '''
    filename_all_stuff_info  :
              字典类型，由result_dict 过滤掉姓名转化，
              结构是：{"2017_06_24":{name1: [walk_num， time], name2: [walk_num, time],... }}
    '''
    filename_all_stuff_info = filter_name_time(result_dict)
#    print (filename_all_stuff_info, '\n \n')
    save_to_xls(filename_all_stuff_info)
  
  